import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    getId: 9,
    key: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    inputChange(state, value) {
      state.inputValue = value
    },
    addItem(state) {
      const obj = {
        id: state.getId++,
        info: state.inputValue.trim(),
        done: false
      }
      state.inputValue = ''
      state.list.unshift(obj)
    },
    removeItem(state, id) {
      const i = state.list.findIndex((x) => x.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    checkDone(state, id) {
      const i = state.list.findIndex((x) => x.id === id)
      if (i !== -1) {
        state.list[i].done = !state.list[i].done
      }
    },
    cleanDone(state) {
      state.list = state.list.filter((x) => x.done === false)
    },
    changeBtn(state, param) {
      if (param === 'all') {
        state.key = 'all'
      } else if (param === 'undone') {
        state.key = 'undone'
      } else {
        state.key = 'done'
      }
    }
  },
  actions: {
    getList(context) {
      axios.get('/data.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLength(state) {
      return state.list.filter((x) => x.done === false).length
    },
    infoList(state) {
      if (state.key === 'all') {
        return state.list
      } else if (state.key === 'undone') {
        return state.list.filter((x) => x.done === false)
      } else if (state.key === 'done') {
        return state.list.filter((x) => x.done === true)
      }
      return state.list
    }
  },
  modules: {}
})
